package com.soo.hoo.admin.utils;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaStorage;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import com.soo.hoo.admin.model.vo.UserVO;

/**
 * <p>
 * sa登录鉴权工具
 * </p>
 *
 * @author 杨燚
 * @since 2024/5/17
 */
public class SaLoginUtil {


    private static final String LOGIN_USER_KEY = "login-user";
    private static final String USER_ID_KEY = "user-id";

    /**
     * 登录
     *
     * @param user 用户信息
     */
    public static void login(UserVO user) {
        SaStorage storage = SaHolder.getStorage();
        storage.set(LOGIN_USER_KEY, user);
        storage.set(USER_ID_KEY, user.getId());
        StpUtil.getSession().set(LOGIN_USER_KEY, user);
    }

    /**
     * 获取已登录用户信息
     *
     * @return 已登录的用户信息
     */
    public static UserVO getUser() {
        UserVO user = (UserVO) SaHolder.getStorage().get(LOGIN_USER_KEY);
        if (user != null) {
            return user;
        }
        SaSession session = StpUtil.getSession();
        if (ObjUtil.isNotNull(session)) {
            Object o = session.get(LOGIN_USER_KEY);
            user = Convert.convert(UserVO.class, o);
            SaHolder.getStorage().set(LOGIN_USER_KEY, user);
            return user;
        }
        return null;
    }

    /**
     * 根据token获取登录用户信息
     *
     * @param token token
     * @return 已登录的用户信息
     */
    public static UserVO getUser(String token) {
        Object loginId = StpUtil.getLoginIdByToken(token);
        SaSession session = StpUtil.getSessionByLoginId(loginId);
        if (session != null) {
            return ((UserVO) session.get(LOGIN_USER_KEY));
        }
        return null;
    }

    /**
     * 获取已登录的用户id
     *
     * @return 已登录的用户id
     */
    public static Long getUserId() {
        return StpUtil.getLoginIdAsLong();
    }

}
